<template>
	<view>
		<uni-section class="section-box" title="" subTitle="">
			<uni-search-bar radius="100" placeholder="搜索" bgColor="#EEEEEE" @input="onKeyInput" @confirm="search" />
		</uni-section>
		<uni-section class="section-box" title="" type="" v-if='formulaList && formulaList.length>0'>
			<uni-list v-for="(formula,index) in formulaList" :key="index" @click="toggle(formula,index)">
				<uni-list-item :title="formula.name" :note="formula.formula" rightText="" :style="{'background-color':formula.is_top == 1 ? 'aliceblue':'#fff'}"/>
			</uni-list>
		</uni-section>
		<view class="container" v-else>
			<text class="noText">暂无数据</text>
		</view>
		
		<!-- </navigator> -->

		<view class="uni-loadmore" v-if="showLoadMore">{{loadMoreText}}</view>
		<uni-fab ref="fab" :pattern="pattern" :content="content" :horizontal="horizontal" :vertical="vertical"
			:direction="direction" @trigger="trigger" @fabClick="fabClick" />
	    <view>
	    	<!-- 普通弹窗 -->
	    	<uni-popup ref="popup" background-color="#fff" style="height: 300px;">
	    		<view class="popup-content" :class="{ 'popup-height': type === 'left' || type === 'right' }">
					<uni-list style="text-align: center;color: #3e99ef;">
							<text class="slot-text" @click="editFormula(popup,'length')">纸长公式</text>
							<text class="slot-text" @click="editFormula(popup,'height')">纸度公式</text>
							<text class="slot-text" @click="editFormula(popup,'edit')">编辑公式</text>
							<text class="slot-text" v-if="isdin == 0" @click="setTop(popup)">置顶公式</text>
							<text class="slot-text" v-if="isdin == 1" @click="setTop(popup)">取消置顶</text>
							<!-- <text class="slot-text" @click="copy(popup)">复制公式</text> -->
							<text class="slot-text" @click="del(popup)">删除公式</text>
							<text class="slot-text" @click="cancel(popup)">取消</text>
							
					</uni-list>
			</view>
	    	</uni-popup>
	    </view>
	</view>
</template>

<script>
	import h5Copy from '../../common/h5copy.js';
	import * as util from '@/common/util.js';
	import { delFormula,setFormula} from '@/common/api'
	export default {
		data() {
			return {
				title: '参考公式',
				formulaid:0,
				contformula:[],
				isdin:0,
				msgType: 'success',
				messageText: '这是一条成功提示',
				type: 'center',
				types: 'center',
				vedit: 0,
				tagformla:'',
				index:0,
				directionStr: '垂直',
				horizontal: 'right',
				vertical: 'bottom',
				count: 0,
				direction: 'horizontal',
				pattern: {
					color: '#7A7E83',
					backgroundColor: '#fff',
					selectedColor: '#009776',
					buttonColor: '#009776',
					iconColor: '#fff'
				},
				loadMoreText: "",
				showLoadMore: false,
				max: 0,
				is_color_type: false,
				content: [],
				formulaList: [],
				newformula: [],
				comformula:0,
				userinfo:[],
				userid:0,
				commonArr:{},
				formula_len:'',
				formula_degree:'',
			}
		},
		
		onLoad(options) {
			uni.showLoading({
				title: "Loading",
				duration: 2000,//提示的延迟时间，单位毫秒，默认：1500
			})
			this.max = 10,
			// this.initData();
			// this.loadMoreText = "加载更多",
			this.showLoadMore = false;
			
			this.setListData();
			
		},
		onReachBottom() {
			if (this.max > this.count) {
				this.loadMoreText = "没有更多数据了!"
				return;
			}
			this.showLoadMore = true;
			setTimeout(() => {
				this.setListData();
			}, 300);
		},
		onReady() {
			uni.hideLoading();
		},
		onPullDownRefresh() {
			console.log('onPullDownRefresh');
			this.initData();
		},
		methods: {
			onNavigateTo(id) {
				console.log(id,"监听到返回事件");
				this.setListData();
				// window.location.reload();
				// let datas = [];
				// this.max += 10;
				// datas = [
				//  //  {
				// 	// id: 25,
				// 	// name: '纸箱(特殊纸箱1)',
				// 	// formula:'长*宽*高*(2+3+4)*来价'
				//  //  },
				// ]
				// this.formulaList = this.formulaList.concat(datas);
			},
			setListData(){
				let userInfo = uni.getStorageSync('userInfo');
				if(!userInfo){
					uni.showToast({
						title: '登录失效,重新登录',//标题 必填
						icon: 'none',//图标
					    mask: false,//是否显示透明蒙层，防止触摸穿透，默认：false
					    duration: 2000,//提示的延迟时间，单位毫秒，默认：1500
					});
					setTimeout(function () {
						uni.navigateTo({
							url: '/pages/login/login'
						});
					}, 2000);
				}
				let formula = uni.getStorageSync('formula');
				userInfo = JSON.parse(userInfo);
				this.userinfo = userInfo;
				this.userid = userInfo.user_id;
				formula = JSON.parse(formula);
				console.log(formula);
				this.contformula = formula;
				let newformula = [];
				let a = [];
				let newformula_lenArr = [];
				let newformula_degreeArr = [];
				let len = 0;
				
				formula.sort(function(a, b) {
					// 比较A值
				    if (a.is_top != b.is_top) {
					 return a.is_top > b.is_top ? -1 : 1;
				      // return b.is_top - a.is_top;
				    }
					// // 如果A值相同，比较B值
					// return b.updated_at - a.updated_at;
				    return a.updated_at > b.updated_at ? -1 : 1;
				});
				
				formula.forEach((i,index)=>{
					let formulaArr = [];
					let keys = i.private_formula_id.toString();
					formulaArr.id = i.private_formula_id;
					formulaArr.name = i.name;
					formulaArr.is_top = i.is_top;
					formulaArr.formula_len = util.strReplace(i.formula_len);
					formulaArr.formula_degree = util.strReplace(i.formula_degree);
					formulaArr.oldformula = i.formula;
					formulaArr.user_id = i.user_id;
					//字符替换
					var newformulastr = util.strReplace(i.formula);
					
					formulaArr.formula = newformulastr;
					
					// formulaArr.text = i.name;
					newformula.push(formulaArr);
					a[keys] = i.formula;
					newformula_lenArr[keys] = i.formula_len;
					newformula_degreeArr[keys] = i.formula_degree;
					len++;
					
				})
				this.newformulaArr = a;
				this.newformula_lenArr = newformula_lenArr;
				this.newformula_degreeArr = newformula_degreeArr;
				this.count = len;
				this.newformula = newformula;
				this.formulaList = newformula;
			},
			onKeyInput: function(event) {
				if(event == ''){
					this.formulaList = this.newformula;
					return
				}
				const item = this.newformula.filter(obj =>
				  String(obj['name']).toLowerCase().includes(event.toLowerCase()),
				);
				// const item = this.newformula.find(item => item.name == res.value);
				if(!item){
					this.formulaList = [];
					return;
				}
				let newitem = [];
				item.forEach((i,index)=>{
					let formulaArr = [];
					
					formulaArr.id = i.id;
					formulaArr.user_id = i.user_id;
					formulaArr.formula = i.formula;
					formulaArr.formula_degree = i.formula_degree;
					formulaArr.formula_len = i.formula_len;
					formulaArr.is_top = i.id;
					formulaArr.name = i.name;
					formulaArr.oldformula = i.oldformula;
					newitem.push(formulaArr);
				});
				console.log(newitem)
				this.formulaList = newitem;
			},
			search(res) {
				if(res.value == ''){
					this.formulaList = this.newformula;
					return
				}
				const item = this.newformula.filter(obj =>
				  String(obj['name']).toLowerCase().includes(res.value.toLowerCase()),
				);
				// const item = this.newformula.find(item => item.name == res.value);

				if(!item){
					this.formulaList = [];
					return;
				}
				let newitem = [];
				item.forEach((i,index)=>{
					let formulaArr = [];
					formulaArr.id = i.id;
					formulaArr.user_id = i.user_id;
					formulaArr.formula = i.formula;
					formulaArr.formula_degree = i.formula_degree;
					formulaArr.formula_len = i.formula_len;
					formulaArr.is_top = i.id;
					formulaArr.name = i.name;
					formulaArr.oldformula = i.oldformula;
					newitem.push(formulaArr);
				});
				this.formulaList = newitem;
				
			},
			
			onPullDownRefresh() {
				console.log('onPullDownRefresh');
				// this.initData();
			},
			toggle(data,index) {
				this.index = index;
				this.commonArr.private_formula_id = data.id;
				this.commonArr.formula = data.oldformula;
				this.isdin = data.is_top;
				this.commonArr.is_top = data.is_top;
				this.commonArr.name = data.name;
				this.commonArr.formula_len = data.formula_len;
				this.commonArr.formula_degree = data.formula_degree;
				this.commonArr.user_id = data.user_id;
				this.comformula = data.id;
				//公式
				this.tagformla = data.formula;
				this.is_top = data.is_top;
				this.formula_len = data.formula_len;
				this.formula_degree = data.formula_degree;
				console.log(this.commonArr);
				var type = 'bottom';
				// this.isHiddenbtn = true;
				this.type = type;
				// open 方法传入参数 等同在 uni-popup 组件上绑定 type属性
				this.$refs.popup.open(type);
			},
			trigger(e) {
				console.log("ssssss")
				
			},
			editFormula(res,types){
				console.log(this.tagformla);
				uni.navigateTo({
					url: '/pages/index/addformula?types='+types+'&id='+this.comformula+'&formula_len='+this.formula_len+'&formula_degree='+this.formula_degree+'&formula='+this.tagformla+'&name='+this.commonArr.name
				})
				this.$refs.popup.close();
			},
			fabClick() {
				uni.navigateTo({
					url: '/pages/index/addformula'
				})
				this.$refs.popup.close();
			},
			input(res) {
				console.log('----input:', res)
			},
			clear(res) {
				uni.showToast({
					title: 'clear事件，清除值为：' + res.value,
					icon: 'none'
				})
			},
			blur(res) {
				uni.showToast({
					title: 'blur事件，输入值为：' + res.value,
					icon: 'none'
				})
			},
			focus(e) {
				uni.showToast({
					title: 'focus事件，输出值为：' + e.value,
					icon: 'none'
				})
			},
			del(res) {
				let hash = 'acbcefg';
				let timestamp = Math.round(new Date().getTime() / 1000).toString();
				delFormula({user_id:this.userid,private_formula_id:this.comformula,hash:hash,timestamp:timestamp}).then(resData=>{
					
					if(resData.code == '200'){
						uni.showToast({
							title: "删除成功",
							 duration: 2000,//提示的延迟时间，单位毫秒，默认：1500
						})
						//更新数据
						uni.setStorageSync('formula',JSON.stringify(resData.data.private_formula));
						this.formulaList = util.sortReplace(resData.data.private_formula);
					
					}else{
						uni.showToast({
							title: resData.msg,//标题 必填
							icon: 'none',//图标
						    mask: false,//是否显示透明蒙层，防止触摸穿透，默认：false
						    duration: 2000,//提示的延迟时间，单位毫秒，默认：1500
						});
						return
					}
					this.$refs.popup.close()
				}).catch(
					(response) => {
						console.log("失败")
						uni.showToast({
							title: "系统错误"+response.message,//标题 必填
							icon: 'none',//图标
						    mask: false,//是否显示透明蒙层，防止触摸穿透，默认：false
						    duration: 2000,//提示的延迟时间，单位毫秒，默认：1500
						});
						this.$refs.popup.close()
					}
				)
			},
			cancel(res) {
				this.$refs.popup.close();
				
			},
			// 复制公式
			copy() {
				let content = this.tagformla // 复制内容，必须字符串，数字需要转换为字符串
				    const result = h5Copy(content)
				    if (result === false) {
				        uni.showToast({
				            title: '不支持',
				        })
				    } else {
				        uni.showToast({
				           title: '复制成功',
				            icon: 'none'
				        })
				
				    }
				this.$refs.popup.close();
			},
			setTop(res){
				uni.showLoading({
					title: "Loading",
					duration: 1500,//提示的延迟时间，单位毫秒，默认：1500
				})
				// let commonArr = this.commonAr;
				let hash = 'acbcefg';
				let timestamp = Math.round(new Date().getTime() / 1000).toString();
				let is_top = this.commonArr.is_top;
				
				let private_formula_id = this.commonArr.private_formula_id;
				
				let formula = this.commonArr.formula;
				// console.log(this.commonArr);return;
				formula = util.restrReplace(formula);
				let name = this.commonArr.name;
				let formula_len = this.commonArr.formula_len;
				
				formula_len = util.restrReplace(formula_len);
				let formula_degree = this.commonArr.formula_degree;
				formula_degree = util.restrReplace(formula_degree);
				let user_id = this.commonArr.user_id;
				
				if(is_top == 1){
					is_top = 0;
				}else if(is_top == 0){
					is_top = 1;
				}
				// this.isdin = is_top;
				console.log(is_top);
				setFormula({
					formula:formula,
					user_id:user_id,
					is_top:is_top,
					private_formula_id:private_formula_id,
					formula_len:formula_len,
					formula_degree:formula_degree,
					name:name,
					hash:hash,
					timestamp:timestamp,
				}).then(resData=>{
					
					if(resData.code == '200'){
						
						//更新数据
						uni.setStorageSync('formula',JSON.stringify(resData.data.private_formula));
						
						this.formulaList = util.sortReplace(resData.data.private_formula);
						
						uni.hideLoading();
					}else{
						uni.showToast({
							title: res.msg,//标题 必填
							icon: 'none',//图标
						    mask: false,//是否显示透明蒙层，防止触摸穿透，默认：false
						    duration: 2000,//提示的延迟时间，单位毫秒，默认：1500
						});
						return
					}
					
				}).catch(
					(response) => {
						uni.showToast({
							title: "系统错误"+response.message,//标题 必填
							icon: 'none',//图标
						    mask: false,//是否显示透明蒙层，防止触摸穿透，默认：false
						    duration: 2000,//提示的延迟时间，单位毫秒，默认：1500
						});
					}
				);
				this.$refs.popup.close();
			},
		},
		mounted() {
			console.log("监听到返回事件1");
			// window.location.reload();
		    // 监听返回事件并刷新页面
		    uni.$on('back', this.onNavigateTo)
		},
		beforeDestroy() {
		    // 移除返回事件
		    // uni.$off('back', this.onNavigateTo)
		},
		onBackPress() {
			// #ifdef APP-PLUS
			plus.key.hideSoftKeybord();
			// #endif
		},
		
	}
</script>

<style lang="scss">
	::v-deep.section-box,.uni-section{
		.uni-section-header {
			padding: 0 !important;
			display: none;
		}
	}
	.warp {
		padding: 10px;
	}
	.center-list-main {
		flex: 1;
	}
	.button {
		margin-bottom: 10px;
	}
	.search-result {
		padding-top: 10px;
		padding-bottom: 20px;
		text-align: center;
	}

	.search-result-text {
		text-align: center;
		font-size: 14px;
		color:#666;
	}
	 .container {
	    display: flex;
	    justify-content: center;
	    align-items: center;
	    width: 100vw;
	    height: 75vh;
	  }
	  .img-item {
	    width: 50%;
	    // height: auto;
	  }	
	  .noText{
		  margin-top: 0.3125rem;
		  font-size: 0.875rem;
		  height: 1.375rem;
		  line-height: 1.375rem;
		  font-family: Source Han Sans CN, Source Han Sans CN;
		  font-weight: 400;
		  color: #999999;
	  }
	.example-body {
		/* #ifndef APP-NVUE */
		display: block;
		/* #endif */
		padding: 0px;
	}

	.uni-mt-10 {
		margin-top: 10px;
	}
	.slot-box {
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		flex-direction: row;
		align-items: center;
	}
	.slot-text {
		flex: 1;
		font-size: 14px;
		color: royalblue;
		height: 50px;
		line-height: 50px;
		border-bottom: 3px solid #F5F5F5;
	}
	.slot-text-delfrom{
		flex: 1;
		font-size: 17px;
		color: royalblue;
		height: 60px;
		line-height: 50px;
		margin-top: 5px;;
		border-bottom: 3px solid #F5F5F5;
	}
</style>
